package com.qulai.amazon_us.util.basic;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.annotation.NoClass;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LlmApiUtil {



    public static final String AMAZON_US_POST_PROMPT = "Generate an Amazon post title based on the product info provided that:\n" +
            "\uFEFF\n" +
            "Highlights Key Features and Brand Identity: Emphasize the core functionality and benefits of the product while creating a sense of branding or identity. Make sure the title reflects the unique selling points of the product.\n" +
            "\uFEFF\n" +
            "Compatibility Mention: If applicable, include compatibility details such as \"compatible with X\" or \"works with Y,\" but ensure the main product is listed first in the title.\n" +
            "\uFEFF\n" +
            "Clear Call to Action (CTA): If a CTA is used, it must be clear, specific, and actionable. Avoid vague phrases like \"Click here\" or other ambiguous CTAs.\n" +
            "\uFEFF\n" +
            "Relevant Keywords: Use carefully selected, relevant keywords that are appropriate for the product and complement the visuals in the post (images or videos). The title should not include product descriptions or customer reviews.\n" +
            "\uFEFF\n" +
            "Length and Readability: Keep the title concise and within 300 characters to ensure readability and engagement.The result should be strictly returned in JSON format, for example: {\"title\": \"\"}";

    private static final String API_URL = "https://treatlife.openai.azure.com/openai/deployments/%s/chat/completions?api-version=2024-10-21";
    private static final String[] API_KEYS = {"1oiNn7T7SjwhqFDA2TpRqoBezw8yzI8N88Zbh8emel61hVJv7P8oJQQJ99BEACYeBjFXJ3w3AAABACOGzL4o", "5o0jchoQZYCvM69j6H6CaavC29V6YiPz9Nj5wR8o5ncXpZTfcJy3JQQJ99BEACYeBjFXJ3w3AAABACOGohWQ"}; // 请替换为实际的 API 密钥

    /**
     * 从文本中提取并解析 JSON 部分
     *
     * @param text 输入的文本
     * @return 解析后的 JSONObject，若无有效 JSON 则返回空 JSONObject
     */
    public static JSONObject extractAndMergeJson(String text) {
        // 检查输入是否为空
        if (text == null || text.trim().isEmpty()) {
            return new JSONObject();
        }

        try {
            // 使用正则表达式匹配 JSON 对象或数组
            Pattern pattern = Pattern.compile("\\{.*?\\}|\\[.*?\\]", Pattern.DOTALL);
            Matcher matcher = pattern.matcher(text);
            if (matcher.find()) {
                String jsonString = matcher.group();
                return JSON.parseObject(jsonString); // 使用 fastjson2 解析 JSON
            } else {
                System.out.println("没有找到有效的 JSON 部分: " + text);
                return new JSONObject();
            }
        } catch (Exception e) {
            System.out.println("JSON 解析错误: " + e.getMessage());
            return new JSONObject();
        }
    }

    /**
     * 发送请求到 OpenAI API 并获取响应
     *
     * @param isJson      是否返回 JSON 格式
     * @param contentText 用户输入内容
     * @param systemText  系统提示内容
     * @param model       使用的模型，默认为 "gpt-4o-mini"
     * @param tryCount    重试次数
     * @return 根据 isJson 参数返回 JSONObject 或 String，若失败则返回空值
     */
    public static Object openaiRsp(boolean isJson, String contentText, String systemText, String model, Integer tryCount) {
        if(model == null || model.trim().isEmpty()) {
            model = "gpt-4o-mini";
        }
        if (tryCount == null) {
            tryCount = 2;
        }
        String url = String.format(API_URL, model);
        HttpClient client = HttpClient.newHttpClient();
        String apiKey = API_KEYS[(int) (System.currentTimeMillis() / 1000) % 2]; // 轮询选择 API 密钥

        // 构建请求体
        JSONObject data = new JSONObject();
        data.put("messages", new Object[]{
                new JSONObject().fluentPut("role", "system").fluentPut("content", systemText),
                new JSONObject().fluentPut("role", "user").fluentPut("content", contentText)
        });

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/json")
                .header("api-key", apiKey)
                .POST(HttpRequest.BodyPublishers.ofString(data.toJSONString()))
                .build();

        // 重试逻辑
        for (int attempt = 0; attempt < tryCount; attempt++) {
            try {
                HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
                if (response.statusCode() == 200) {
                    String resText = JSON.parseObject(response.body())
                            .getJSONArray("choices")
                            .getJSONObject(0)
                            .getJSONObject("message")
                            .getString("content");
                    if (isJson) {
                        return extractAndMergeJson(resText);
                    }
                    return resText;
                } else {
                    System.out.println("请求失败, 状态码: " + response.statusCode());
                }
            } catch (IOException | InterruptedException e) {
                if (!e.getMessage().contains("connect timeout") && !e.getMessage().contains("timed out")) {
                    System.out.println("请求出错了, 错误原因: " + e.getMessage());
                }
                try {
                    Thread.sleep(5000); // 失败后等待 1 秒再重试
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                }
            }
        }
        return isJson ? new JSONObject() : ""; // 所有尝试失败后返回默认值
    }

    public static void main(String[] args) {
         String PRODUCT_INFO = "<p><strong>Product Overview</strong><br>This versatile kitchen island stands at a height of 35 inches and features a unique blend of functionality and style. The product boasts a single-door cabinet that provides secure storage for kitchen essentials and valuables.</p><p><strong>Core Features and Advantages</strong><br>The expansive tabletop measures 40.5 inches by 27.5 inches, making it suitable for various activities from food preparation to serving. The open storage shelf allows for effective display of culinary supplies or decorative items while adding a touch of elegance to your kitchen space.</p><p><strong>Ideal Usage Scenarios</strong><br>This kitchen island serves as both a practical solution for additional storage and a stylish centerpiece in the kitchen. It's  for organizing pots, pans, and utensils with its two internal shelves, making it ideal for both busy households and culinary enthusiasts.</p><p><strong>Materials and Craftsmanship</strong><br>Crafted from durable particle board, this kitchen island is built to withstand the rigors of daily use. Its white and macadamia finish adds a modern touch to your kitchen d\\u00e9cor, ensuring that it complements various color schemes and styles.</p><p><strong>Care Instructions</strong><br>Maintaining this kitchen island is simple. Regularly dust the surfaces with a damp cloth, and avoid harsh chemicals to ensure longevity. This easy care routine will keep your kitchen island looking beautiful for years to come.</p>";
        String res = (String) openaiRsp(false,PRODUCT_INFO, AMAZON_US_POST_PROMPT, null,null);
        System.out.println(res);
    }
}
